package com.rabbitmq.config.dlx;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 王霄
 * @date 2022/1/8 20:51
 */
@Configuration
public class DLXConfig {

    public static final String DLX_EXCHANGE_NAME = "dlx.exchange";
    public static final String DLX_QUEUE = "dlx.queue";
    public static final String DLX_ROUTING_KEY = "dlx.routing.key";


    public static final String ORDER_EXCHANGE_NAME = "order.exchange";
    public static final String ORDER_QUEUE = "order.queue";
    public static final String ORDER_ROUTING_KEY = "order.routing.key";


    @Bean(DLX_EXCHANGE_NAME)
    public DirectExchange dlxExchange() {
        return new DirectExchange(DLX_EXCHANGE_NAME);
    }

    @Bean(DLX_QUEUE)
    public Queue dlxQueue() {
        Map<String, Object> arguments = new HashMap<>(2);
        arguments.put("x-dead-letter-exchange", ORDER_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key", ORDER_ROUTING_KEY);
        arguments.put("x-message-ttl", 1000 * 60);
        arguments.put("x-max-length", 10);
        return new Queue(DLX_QUEUE, true, false, false, arguments);
    }

    @Bean
    public Binding bindingDlxExchange() {
        return BindingBuilder
                .bind(dlxQueue())
                .to(dlxExchange())
                .with(DLX_ROUTING_KEY);
    }

    @Bean(ORDER_EXCHANGE_NAME)
    public DirectExchange orderExchange() {
        return new DirectExchange(ORDER_EXCHANGE_NAME);
    }

    @Bean(ORDER_QUEUE)
    public Queue orderQueue() {
        return new Queue(ORDER_QUEUE);
    }

    @Bean
    public Binding orderDelayTranspondQueueBindExchange() {
        return BindingBuilder
                .bind(orderQueue())
                .to(orderExchange())
                .with(ORDER_ROUTING_KEY);
    }

}
